package com.codeyourlife.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.codeyourlife.dao.UserDao;
import com.codeyourlife.entity.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void addUser(User user) {
		this.getSessionFactory().getCurrentSession().save(user);
	}

	public void deleteUser(String email) {
		sessionFactory.getCurrentSession().delete(getUser(email));
	}

	public void deleteUser(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}

	@SuppressWarnings("unchecked")
	public void updateUser(User user) {
		Query query = this.getSessionFactory().getCurrentSession()
				.createQuery("from User u where u.email='" + user.getEmail() + "'");
		List<User> list = query.list();
		User user_new=list.get(0);
		user_new.setPassword(user.getPassword());
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		session.update(user_new);
		session.getTransaction().commit();
		session.close();
	}

	public User getUser(String email) {
		Session session=sessionFactory.getCurrentSession();
		User user = session.load(User.class, email);
		session.close();
		return user;
	}

	@SuppressWarnings("unchecked")
	public User findByName(String email) {
		 
		try {
			Session session=this.getSessionFactory().getCurrentSession();
			Query query = session.createQuery("from User u where u.email='" + email + "'");
			List<User> list = query.list();
			return list.get(0);
		} catch (Exception e) {
			System.out.println("UserDaoImpl: " + e.getStackTrace());
		}
		return null;
	}

	public List<User> findAllUser() {
		 
		return null;
	}

	@SuppressWarnings("unchecked")
	public User logincheck(String email, String password) {
		Query query = sessionFactory.getCurrentSession()
				.createQuery("from User u where u.email='" + email + "' and u.password='" + password + "'");
		List<User> list = query.list();
		try {
			return list.get(0);
		}catch(Exception e){
			System.out.println(e.toString());
		}
		return null;
	}
}